<template>
  <div style="width: 100%">
    <vxe-pulldown ref="xDown" v-model="selectValue" style="width: 100%">
      <template #default>
        <vxe-input
          v-model="treeValue"
          clearable
          :disabled="disabledSel"
          :placeholder="placeholder"
          readonly="readonly"
          :style="{ width: width }"
          type="search"
          @clear="clearInput"
          @click="showTreeePanel"
          @search-click="handleSearchClick"
        />
      </template>
      <template #dropdown>
        <!--      <el-scrollbar>-->
        <el-input v-if="searchable" v-model="filterText" placeholder="输入关键字进行过滤" style="width: 100%" />
        <vxe-table
          ref="xTable"
          auto-resize
          :checkbox-config="{
            labelField: 'nodename',
            highlight: true,
            checkRowKeys: checkRowKeys,
            checkStrictly: checkStrictlyRef,
            visibleMethod: handleVisibleMethod
          }"
          :data="tableData"
          max-height="300px"
          :row-config="{ keyField: 'id' }"
          :show-header="false"
          show-overflow
          :tree-config="{
            transform: true,
            rowField: 'id',
            parentField: 'parentid',
            expandRowKeys: expandRowKeys
          }"
          @checkbox-change="handleCheckboxChange"
        >
          <vxe-column tree-node type="checkbox" />
        </vxe-table>
        <!--      </el-scrollbar>-->
      </template>
    </vxe-pulldown>
  </div>
</template>

<script setup>
import { postRequest } from "@/api/mains";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => {
      return [];
    }
  },
  data: {
    type: Array,
    default: () => {
      return [];
    }
  },
  url: {
    type: String,
    default: () => {
      return "";
    }
  },
  queryForm: {
    type: Object,
    default: () => {
      return {};
    }
  },
  placeholder: {
    type: String,
    default: () => {
      return "请选择";
    }
  },
  disabled: {
    type: Boolean,
    default: false
  },
  width: {
    type: String,
    default: "100%"
  },
  checkStrictly: {
    type: Boolean,
    default: () => {
      return true;
    }
  },
  searchable: {
    type: Boolean,
    default: () => {
      return true;
    }
  }
});

const selectValue = ref(props.modelValue);

const emit = defineEmits(["update:model-value", "on-change"]);

const disabledSel = ref(props.disabled);
const checkStrictlyRef = ref(props.checkStrictly);
const filterText = ref();
const queryFormRef = ref(props.queryForm);
const allData = ref([]);
const tableData = ref([]);
//const selectRow = ref() //当前选中的行
const expandRowKeys = ref([]); //默认展开的行
const checkRowKeys = ref([]); //默认勾选的行
const xTable = ref();
const treeValue = ref();
const xDown = ref();

const handleCheckboxChange = () => {
  const rows = xTable.value.getCheckboxRecords(true);
  //const $pulldown2 = xDown.value
  treeValue.value = rows.map(item => item.nodename).join();
  emit(
    "update:model-value",
    rows.map(item => item.id)
  );

  emit("on-change", rows);
};

const showTreeePanel = () => {
  const $pulldown2 = xDown.value;
  $pulldown2.showPanel();
};

const handleSearchClick = () => {
  if (!disabledSel.value) {
    showTreeePanel();
  }
};

/*const keyupEvent2 = () => {
    tableData.value = treeValue.value
      ? allData.value.filter(
          (item) => item.nodename.indexOf(treeValue.value) > -1
        )
      : allData.value
  }*/

const clearInput = () => {
  emit("update:model-value", []);
  emit("on-change", []);
};

const handleFetchTreeData = async () => {
  if (props.url != null && typeof props.url != "undefined" && props.url != "") {
    const responseData = await postRequest(props.url, queryFormRef.value);
    if (responseData.code !== 200) {
      failMsg(responseData.msg);
      return;
    }
    tableData.value = responseData.data.rows;
    allData.value = responseData.data.rows;

    treeValue.value = "";
    const treeNodeNames = [];
    allData.value.forEach(item => {
      if (item.parentid == "root" || item.parentid == "" || item.parentid == "0") {
        expandRowKeys.value.push(item.id);
      }
      if (selectValue != null && selectValue.value.length > 0) {
        const selArr = selectValue;
        checkRowKeys.value = selArr;
        for (let i = 0; i < selArr.length; i++) {
          if (selArr[i] == item.id) {
            treeNodeNames.push(item.nodename);
            //checkRowKeys.value.push(selArr[i])//只能初始化一次
            if (xTable.value != null && typeof xTable.value != "undefined") {
              xTable.value.setCheckboxRow(item, true);
            }
          }
        }
      }
    });
    treeValue.value = treeNodeNames.join();
  }
};

const handleVisibleMethod = row => {
  if (row.row.disabled) {
    return false;
  }
  return true;
};

watch(
  () => props.disabled,
  () => {
    disabledSel.value = props.disabled;
  }
);

watch(
  () => props.data,
  newVal => {
    tableData.value = newVal;
    allData.value = newVal;

    treeValue.value = "";
    const treeNodeNames = [];
    allData.value.forEach(item => {
      if (item.parentid == "root") {
        expandRowKeys.value.push(item.id);
      }
      if (selectValue != null && selectValue.value.length > 0) {
        const selArr = selectValue;
        checkRowKeys.value = selArr;
        for (let i = 0; i < selArr.length; i++) {
          if (selArr[i] == item.id) {
            treeNodeNames.push(item.nodename);
            //checkRowKeys.value.push(selArr[i])//只能初始化一次
            if (xTable.value != null && typeof xTable.value != "undefined") {
              xTable.value.setCheckboxRow(item, true);
            }
          }
        }
      }
    });
    treeValue.value = treeNodeNames.join();
  }
);

watch(
  () => props.modelValue,
  newVal => {
    treeValue.value = "";
    const treeNodeNames = [];
    checkRowKeys.value = [];

    if (xTable.value != null && typeof xTable.value != "undefined") {
      xTable.value.setAllCheckboxRow(false); //取消勾选
      if (newVal == null || newVal.length == 0) {
        xTable.value.clearCheckboxRow();
      }
    }
    allData.value.forEach(item => {
      if (item.parentid == "root" || item.parentid == "" || item.parentid == "0") {
        if (xTable.value != null && typeof xTable.value != "undefined") {
          xTable.value.setTreeExpand(item, true);
        }
      }
      if (newVal != null && newVal.length > 0) {
        const selArr = newVal;
        checkRowKeys.value = selArr;
        for (let i = 0; i < selArr.length; i++) {
          if (selArr[i] == item.id) {
            treeNodeNames.push(item.nodename);
            //checkRowKeys.value.push(selArr[i])//只能初始化一次
            if (xTable.value != null && typeof xTable.value != "undefined") {
              xTable.value.setCheckboxRow(item, true);
            }
          }
        }
      }
    });
    treeValue.value = treeNodeNames.join();
  }
);

watch(
  () => props.url,
  () => {
    handleFetchTreeData();
  }
);

watch(
  () => filterText.value,
  val => {
    console.info(`watch filterText>>>>>>>>${val}`);
    if (val == null || val.trim() == "") {
      tableData.value = allData.value;
    } else {
      const filterdatas = [];
      allData.value.forEach(item => {
        if (item.nodename.indexOf(val) >= 0) {
          filterdatas.push(item);
        }
      });
      tableData.value = filterdatas;
    }
  }
);

onMounted(() => {
  handleFetchTreeData();
});
</script>
<style lang="scss" scoped>
.down-tree {
  width: 100%;
  height: 55vh;
  margin-top: 10px;
  overflow: auto;
}
:deep(.vxe-table--body) {
  .vxe-body--column {
    background-image: none;
  }
}
:deep() {
  .vxe-pulldown--panel {
    min-width: 230px !important;
  }
}
</style>
